import path from 'path';
import { app, BrowserWindow } from 'electron';

import IpcEvent from './event';
import AwakeApp from './core/AwakeApp';
import TrayApplication from './core/Tray';
import ProtocolRegister from './core/Protocol';
import { showTopApplication } from './core/Common';
import startProcess from './core/process/startProcess';
import AwakeChildrenProcess from './core/AwakeChildrenProcess';
import { isDevelopment } from './utils';

let mainWindow: BrowserWindow | null = null;
const iconPath = path.resolve(__dirname, './static/logo.png');
const createWindow = () => {
    const win = new BrowserWindow({
        width: 1200,
        height: 800,
        frame: false,
        icon: iconPath,
        resizable: false,
        webPreferences: { preload: path.resolve(__dirname, './preload.js') }
    });
    win.loadURL((process.env.ELECTRON_URL as string) || `app://./index.html`);
    if (isDevelopment()) win.webContents.openDevTools();
    return win;
};

if (!app.requestSingleInstanceLock()) app.quit(); // 程序启动单例
ProtocolRegister.registerProtocol(); // 自定义协议

app.whenReady().then(() => {
    ProtocolRegister.protocolHandler(); // protocol 协议
    AwakeApp.start(); // schemes 协议
    mainWindow = createWindow();
    startProcess.start(mainWindow); // 将代码作为进程运行
    IpcEvent.register(mainWindow); // Ipc 注册

    // 托盘功能
    TrayApplication.start({
        icon: iconPath,
        mainWindow: mainWindow
    });

    if (isDevelopment()) showTopApplication(mainWindow); // 置顶
    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow();
        }
    });
});

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('will-quit', async () => {
    if (isDevelopment()) {
        AwakeApp.removeSchema();
    }
    await AwakeChildrenProcess.closeAppServices();
});

app.on('second-instance', () => {
    if (mainWindow) showTopApplication(mainWindow);
});
